from typing import List
from elasticsearch_dsl import Search, A


class PipLineSearch:

    def __init__(self, pipelines: List):
        self.pipelines = pipelines

    def execute(self):
        for pipeline in self.pipelines:
            pass


if __name__ == '__main__':
    from common.package.elastic_db import es_db
    es_db.init(hosts='http://192.168.101.79:9200')

    index = 'dsm-1086afd495bd11efae39622bfe3b1ffc'
    raw = {'query': {'match_all': {}}, 'size': 10}

    def raw_test():
        """原始搜索条件搜索"""
        s = Search(using=es_db.client)
        s.from_dict(d=raw)
        resp = s.execute()
        resp = resp.to_dict()
        print(resp)

    def agg_test_1():
        """原始条件搜索 同层级多分组统计"""
        s = Search(using=es_db.client)
        s.from_dict(d=raw)
        s.aggs.bucket('per_host', 'terms', field='_host')  # .pipeline('per_host', 'bucket_sort', sort=[{"per_host": {"order": "desc"}}])  # 分桶
        s.aggs.bucket('per_type', 'terms', field='type')
        a = s.to_dict()
        resp = s.execute()
        resp = resp.to_dict()
        print(resp)

    def agg_test_2():
        """原始条件搜索 多层级分组统计"""
        s = Search(using=es_db.client)
        s.from_dict(d=raw)

        g = A('terms', field='_host')
        g2 = A('terms', field='type')
        g3 = A('terms', field='_sourceid')

        g.bucket('page', 'bucket_sort', sort=[{"_key": {"order": "desc"}}])
        g.bucket('t', g2)
        g2.bucket('s', g3)

        s.aggs.bucket('per_host', g)
        a = s.to_dict()
        resp = s.execute()
        resp = resp.to_dict()
        print(resp)

    def agg_test_3():
        s = Search(using=es_db.client)
        s.from_dict(d=raw)

        g = A('terms', field='_host')

        g3 = A('terms', field='_sourceid', order=[{'v': 'desc'}])

        # g4 = A('value_count', field='_uuid')
        g4 = A('cardinality', field='_uuid')

        g.bucket('page', 'bucket_sort', sort=[{"_key": {"order": "desc"}}])
        g.bucket('s', g3)
        g3.bucket('v', g4)

        s.aggs.bucket('per_host', g)
        a = s.to_dict()
        resp = s.execute()
        resp = resp.to_dict()
        print(a)

    def agg_test_4():
        s = Search(using=es_db.client)
        s.from_dict(d=raw)

        g = A('terms', field='_host', order={'_key': 'desc'})

        s.aggs.bucket('per_host', g)
        a = s.to_dict()
        resp = s.execute()
        resp = resp.to_dict()
        print(a)


    # raw_test()
    # agg_test_1()
    # agg_test_2()
    # agg_test_3()
    agg_test_4()
